using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;

namespace PixelShaderCircles
{
    public class PretransformedQuad
    {
        private GraphicsDevice device;
        private VertexDeclaration decl;
        private QuadVertex[] vertices;
        private short[] indices = { 0, 1, 2, 2, 1, 3 };

        public PretransformedQuad()
        {
        }

        public void Reset(GraphicsDevice device)
        {
            this.device = device;

            decl = new VertexDeclaration(device, QuadVertex.Elements);

            Vector2 texelPixelOffset = new Vector2(0.5f / device.Viewport.Width, 0.5f / device.Viewport.Height);

            vertices = new QuadVertex[]{
                new QuadVertex( new Vector3(-1,  1, 0), new Vector2(0, 0) + texelPixelOffset), // top left
                new QuadVertex( new Vector3( 1,  1, 0), new Vector2(1, 0) + texelPixelOffset), // top right
                new QuadVertex( new Vector3(-1, -1, 0), new Vector2(0, 1) + texelPixelOffset), // bottom left
                new QuadVertex( new Vector3( 1, -1, 0), new Vector2(1, 1) + texelPixelOffset), // bottom right
            };
        }

        public void Dispose()
        {
            if (decl != null)
            {
                decl.Dispose();
                decl = null;
            }
        }

        public void Render()
        {
            Shaders.ShaderEffect.CircleRendering.Render(
                   "Circle",
                   delegate
                   {
                       XnaElite.BaseGame.Device.VertexDeclaration = decl;
                       XnaElite.BaseGame.Device.DrawUserIndexedPrimitives<QuadVertex>(PrimitiveType.TriangleList, vertices, 0, 4, indices, 0, 2);
                   });
            
        }

    }

    struct QuadVertex
    {
        public Vector3 Position;
        public Vector2 Tex0;

        public QuadVertex(Vector3 p, Vector2 t)
        {
            this.Position = p;
            this.Tex0 = t;
        }

        public static VertexElement[] Elements = {
            new VertexElement(0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0),
            new VertexElement(0, 3 * 4, VertexElementFormat.Vector2, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 0)
        };

        public static int Stride = 5 * 4;
    }
}
